<template>
  <div class="dish-manage">
    <div class="page-header">
      <div class="header-title">菜品管理</div>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddDish">添加菜品</el-button>
      </div>
    </div>

    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="所属餐厅">
          <el-select v-model="searchForm.restaurantId" placeholder="请选择" clearable style="width: 200px;">
            <el-option
              v-for="item in restaurantOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜品名称">
          <el-input v-model="searchForm.keyword" placeholder="输入菜品名称"></el-input>
        </el-form-item>
        <el-form-item label="菜品分类">
          <el-select v-model="searchForm.category" placeholder="请选择" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="dishList"
      border
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column label="菜品图片" width="120">
        <template slot-scope="scope">
          <el-image
            style="width: 80px; height: 80px"
            :src="scope.row.image"
            fit="cover"
            :preview-src-list="[scope.row.image]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="菜品名称" width="150"></el-table-column>
      <el-table-column prop="restaurantName" label="所属餐厅" width="150"></el-table-column>
      <el-table-column prop="category" label="分类" width="120"></el-table-column>
      <el-table-column prop="price" label="价格" width="100">
        <template slot-scope="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="100"></el-table-column>
      <el-table-column prop="sales" label="销量" width="100"></el-table-column>
      <el-table-column prop="description" label="描述" min-width="200"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEditDish(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDeleteDish(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>

    <!-- 菜品表单对话框 -->
    <el-dialog 
      :title="dialogType === 'add' ? '添加菜品' : '编辑菜品'" 
      :visible.sync="dialogVisible"
      width="600px"
    >
      <el-form :model="dishForm" :rules="rules" ref="dishForm" label-width="100px">
        <el-form-item label="所属餐厅" prop="restaurantId">
          <el-select v-model="dishForm.restaurantId" placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="item in restaurantOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="dishForm.name"></el-input>
        </el-form-item>
        <el-form-item label="菜品分类" prop="category">
          <el-select v-model="dishForm.category" placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜品图片" prop="image">
          <el-input v-model="dishForm.image" placeholder="图片URL"></el-input>
        </el-form-item>
        <el-form-item label="菜品价格" prop="price">
          <el-input-number v-model="dishForm.price" :min="0" :precision="2" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="dishForm.stock" :min="0" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dishForm.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜品介绍" prop="description">
          <el-input type="textarea" v-model="dishForm.description" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDishForm" :loading="submitting">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'DishManage',
  data() {
    return {
      loading: false,
      submitting: false,
      dishList: [],
      restaurantOptions: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchForm: {
        restaurantId: '',
        keyword: '',
        category: ''
      },
      categoryOptions: [
        { value: '热菜', label: '热菜' },
        { value: '凉菜', label: '凉菜' },
        { value: '主食', label: '主食' },
        { value: '小吃', label: '小吃' },
        { value: '饮品', label: '饮品' },
        { value: '甜点', label: '甜点' },
        { value: '套餐', label: '套餐' }
      ],
      dialogVisible: false,
      dialogType: 'add', // 'add' or 'edit'
      dishForm: {
        id: '',
        restaurantId: '',
        name: '',
        category: '',
        image: 'https://img.yzcdn.cn/vant/cat.jpeg',
        price: 0,
        stock: 0,
        status: 1,
        description: ''
      },
      rules: {
        restaurantId: [
          { required: true, message: '请选择所属餐厅', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入菜品名称', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择菜品分类', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入菜品价格', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '请输入库存', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchRestaurantOptions()
    
    // 如果路由参数中有restaurantId，则设置为当前选中的餐厅
    if (this.$route.query.restaurantId) {
      this.searchForm.restaurantId = Number(this.$route.query.restaurantId)
    }
    
    this.fetchDishList()
  },
  methods: {
    fetchRestaurantOptions() {
      this.$http.get('/admin/restaurant')
        .then(response => {
          this.restaurantOptions = response.data.data
        })
        .catch(error => {
          this.$message.error('获取餐厅列表失败')
          console.error('获取餐厅列表失败', error)
        })
    },
    fetchDishList() {
      this.loading = true
      
      const params = {
        page: this.currentPage,
        size: this.pageSize,
        restaurantId: this.searchForm.restaurantId,
        keyword: this.searchForm.keyword,
        category: this.searchForm.category
      }
      
      this.$http.get('/admin/dish/list', { params })
        .then(response => {
          const { data } = response.data
          this.dishList = data.records
          this.total = data.total
        })
        .catch(error => {
          this.$message.error('获取菜品列表失败')
          console.error('获取菜品列表失败', error)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchDishList()
    },
    resetSearch() {
      this.searchForm = {
        restaurantId: this.$route.query.restaurantId ? Number(this.$route.query.restaurantId) : '',
        keyword: '',
        category: ''
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchDishList()
    },
    handleCurrentChange() {
      this.fetchDishList()
    },
    handleAddDish() {
      this.dialogType = 'add'
      this.dishForm = {
        id: '',
        restaurantId: this.searchForm.restaurantId || '',
        name: '',
        category: '',
        image: 'https://img.yzcdn.cn/vant/cat.jpeg',
        price: 0,
        stock: 0,
        status: 1,
        description: ''
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.dishForm && this.$refs.dishForm.clearValidate()
      })
    },
    handleEditDish(row) {
      this.dialogType = 'edit'
      this.dishForm = { ...row }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.dishForm && this.$refs.dishForm.clearValidate()
      })
    },
    handleDeleteDish(row) {
      this.$confirm('确认删除该菜品？此操作不可恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`/admin/dish/${row.id}`)
          .then(() => {
            this.$message.success('删除成功')
            this.fetchDishList()
          })
          .catch(error => {
            this.$message.error((error.response && error.response.data && error.response.data.message) || '删除失败')
          })
      }).catch(() => {})
    },
    handleStatusChange(row) {
      this.$http.put(`/admin/dish/${row.id}/status`, null, {
        params: { status: row.status }
      })
        .then(() => {
          this.$message.success(`菜品状态已${row.status === 1 ? '上架' : '下架'}`)
        })
        .catch(error => {
          // 恢复状态
          row.status = row.status === 1 ? 0 : 1
          this.$message.error((error.response && error.response.data && error.response.data.message) || '更新状态失败')
        })
    },
    submitDishForm() {
      this.$refs.dishForm.validate(valid => {
        if (valid) {
          this.submitting = true
          
          const request = this.dialogType === 'add'
            ? this.$http.post('/admin/dish', this.dishForm)
            : this.$http.put('/admin/dish', this.dishForm)
          
          request
            .then(() => {
              this.$message.success(this.dialogType === 'add' ? '添加成功' : '更新成功')
              this.dialogVisible = false
              this.fetchDishList()
            })
            .catch(error => {
              this.$message.error((error.response && error.response.data && error.response.data.message) || (this.dialogType === 'add' ? '添加失败' : '更新失败'))
            })
            .finally(() => {
              this.submitting = false
            })
        }
      })
    }
  }
}
</script>

<style scoped>
.dish-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  font-size: 20px;
  font-weight: bold;
}

.search-bar {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}
</style>
